<template>
  <div class="content">
    <a-row type="flex" class="content-row">
      <!-- 索引列 -->
      <a-col flex="50px" class="col-index" v-show="showIndex">
        <ul>
          <li
            v-for="product in data"
            :key="product.key"
            :class="{ productActive: product.key == selectedIndex }"
            @click="indexClick(product.key)"
          >
            <span>
              {{ product.name }}
            </span>
          </li>
        </ul>
      </a-col>

      <a-col flex="auto" class="col-products">
        <a-row class="content-row">
          <a-col :span="levalSpans[0]">
            <ul>
              <li v-for="item in data" :key="item.key">
                <h4 v-if="showIndex">{{ item.key }}</h4>
                <dd>
                  <dl v-for="product in item.products" :key="product.key">
                    <span
                      @click="productItemClick(product, product._fullKey, 0)"
                    >
                      <span
                        :class="{
                          productActive:
                            selectedItems[0] &&
                            selectedItems[0].key == product.key,
                        }"
                        >{{ product.name }}</span
                      >
                      <a-badge
                        :count="getSelectedCount(product._fullKey)"
                        :overflowCount="99999"
                    /></span>
                  </dl>
                </dd>
              </li>
            </ul>
          </a-col>
          <!--动态层级 -->
          <a-col
            v-for="levalItem in leval"
            :key="levalItem"
            :span="dynamicLevalSpans[levalItem - 1]"
          >
            <a-checkbox
              :checked="isAllSelectdByLeval(levalItem - 1)"
              @change="
                (event) =>
                  selectAll(
                    event.target.checked,
                    selectedItems[levalItem - 1]._fullKey
                  )
              "
            >
              全选
            </a-checkbox>

            <ul>
              <li
                v-for="product in getProductChildrenByLeval(levalItem - 1)"
                :key="product.key"
              >
                <span
                  @click="
                    productItemClick(product, product._fullKey, levalItem)
                  "
                  ><span
                    :class="{
                      productActive:
                        selectedItems[levalItem] &&
                        selectedItems[levalItem].key == product.key,
                    }"
                    >{{ product.name }}</span
                  ></span
                >
                <!-- 此处的统计是取子集的选中项 -->
                <a-badge
                  :count="getSelectedCount(product._fullKey)"
                  :overflowCount="99999"
                />
              </li>
            </ul>
          </a-col>

          <!-- 动态层级 end -->

          <!-- 最后一列 -->
          <a-col :span="levalSpans[levalSpans.length - 1]">
            <a-checkbox
              :checked="isAllSelectdByLeval(leval)"
              @change="
                (event) =>
                  selectAll(event.target.checked, selectedItems[leval]._fullKey)
              "
            >
              全选
            </a-checkbox>
            <ul>
              <li
                v-for="product in getProductChildrenByLeval(leval)"
                :key="product.key"
              >
                <a-checkbox
                  :checked="product._selected"
                  @click="selectItem(product._fullKey)"
                  >{{ product.name }}</a-checkbox
                >
              </li>
            </ul>
          </a-col>
        </a-row>
      </a-col>
    </a-row>

    <a-modal
      v-model="isShowSelected"
      width="70%"
      :footer="null"
      :mask="false"
      title="已选"
    >
      <div
        class="result"
        v-if="allSelectedProducts && allSelectedProducts.length > 0"
      >
        <a-table :columns="tableColums" :data-source="allSelectedProducts4Table">
          <span slot="action" slot-scope="text, record">
            <a-button
              size="small"
              @click="deleteFromAllSeletedProducts(record.key)"
              >删除</a-button
            >
          </span>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  props: {
    // 是否显示索引：索引 即 A B C  那层
    showIndex: {
      type: Boolean,
      default: true,
    },
    levalCount: {
      type: Number,
      validator(value) {
        return value >= 3;
      },
      default() {
        return 4;
      },
    },
    levalSpans: {
      type: Array,
      default() {
        return [ 4, 5, 5, 7];
      },
    },
    selectedTableColumnTitles: {
      type: Array,
      default() {
        return ["第1列", "第2列", "第3列", "第4列"];
      },
    },
    dataLoader: {
      type: Function,
      default(product, key, leval, callback) {
        var products = [];
        //模拟查询数据
        for (let i = 0; i < 10; i++) {
          products.push({
            key: key + "-" + i,
            name: key + "-" + i,
          });
        }
        callback(products);
      },
    },
  },

  data() {
    return {
      data: [
        {
          key: "A",
          name: "A",
          products: [
            {
              key: "A-1",
              name: "A-1",
              products: [],
              selectedKeys: [],
              selectedProducts: [],
            },
            {
              key: "A-2",
              name: "A-2",
              products: [],
            },
          ],
        },
        {
          key: "B",
          name: "B",
          products: [
            {
              key: "B-1",
              name: "B-1",
              products: [],
            },
            {
              key: "B-2",
              name: "B-2",
              products: [],
            },
          ],
        },
      ],
      productLists: {},
      selectedItems: {},
      selectedIndex: {},
      isShowSelected: false, //是否显示已选
      // 动态产品列表：点击载入的列表
      dynamicProductList: [],
      allSelectedProducts4Table:[],
      tableColums:[],
    };
  },
  filters: {},
  computed: {
    leval() {
      return this.levalCount - 2;
    },
    dynamicLevalSpans() {
      var spans = [];
      for (let i = 1; i < this.levalSpans.length; i++)
        spans.push(this.levalSpans[i]);

      return spans;
    },
    allSelectedProducts() {
      // 所有选中项
      var products = this.getAllSeletedProducts();
      return products;
    },
    // 源产品列表
    metaProductList() {
      var list = [];

      this.data.forEach((dataItem) => {
        dataItem._preKey = "";
        dataItem._fullKey = dataItem.key;

        let products = dataItem.products;
        products.forEach((product) => {
          this.$set(product, "_preKey", dataItem._fullKey);
          this.$set(product, "_fullKey", dataItem._fullKey + "," + product.key);
          this.$set(product, "_column_"+(dataItem._fullKey.split(',').length-1), dataItem.name);

          if (list.filter((i) => i._fullKey == product._fullKey).length == 0)
            list.push(product);
        });
      });
      return list;
    },
    // 所有的产品列表：整合源数据列表和动态数据列表
    allProductList() {
      return this.metaProductList.concat(this.dynamicProductList);
    },
  },
  watch: {
    allSelectedProducts() {
      console.log(this.allSelectedProducts);
      this.$emit("selectedChange", this.allSelectedProducts.length);
    },
  },
  methods: {
    // 数据载入回调
    dataLoaderCallback(product, productChildren) {
      if (productChildren && productChildren instanceof Array) {
        productChildren.forEach((item) => {

          this.$set(item, "_preKey", product._fullKey);
          this.$set(item, "_fullKey", product._fullKey + "," + item.key);
          this.$set(item, "_column_"+(product._fullKey.split(',').length-1), product.name);
          if (
            this.dynamicProductList.filter((i) => i._fullKey == item._fullKey)
              .length == 0
          )
            this.dynamicProductList.push(item);
        });
      }
    },
    /**型号点击 */
    productItemClick(product, prekey, leval) {
      //判断是否已经载入了数据，是则不重新载入
      if (this.allProductList.filter((p) => p._preKey == prekey).length == 0) {
        //this.$set(product, "products", []);
        //通过外部 loader 获取数据
        //leval+1 是为了方便调用者清楚对应的层级，但是实际上我们只处理  动态层级，即动态载入数据的 层级
        this.dataLoader(product, product.key, leval + 1, (productChildren) =>
          this.dataLoaderCallback(product, productChildren)
        );
      }
      this.$set(
        this.productLists,
        leval,
        this.allProductList.filter((p) => p._preKey == prekey)
      );
      //将当前载入的层级后面的层级的数据置空，不显示
      Object.keys(this.productLists).forEach((k) => {
        if (Number(k) > leval) {
          this.$set(this.productLists, Number(k), []);
          this.$set(this.selectedItems, Number(k), undefined);
        }
      });
      //设置当前层级的选中项为当前产品
      this.$set(this.selectedItems, Number(leval), product);
    },

    getProductChildrenByLeval(leval) {
      if (!this.selectedItems[leval]) return [];
      return this.getProductListByPreKey(this.selectedItems[leval]._fullKey);
    },

    getProductListByPreKey(prekey) {
      return this.allProductList.filter((p) => p._preKey == prekey);
    },

    /**选中选项（最后一列） */
    selectItem(fullkey) {
      this.allProductList
        .filter((p) => p._fullKey == fullkey)
        .forEach((p) => {
          this.$set(p, "_selected", !p._selected);
        });
    },

    selectAllCallback(checked, products, prekey) {
      if (prekey.split(",").length == this.levalCount) {
        products.forEach((p) => this.$set(p, "_selected", checked));
      } else {
        products.forEach((p) => this.selectAll(checked, p._fullKey));
      }
    },

    /*选中所有：当前已选中部分，则清空，否则选中所有 （同时将选中的product记录是为了后面获取选中列表方便）*/
    selectAll(checked, prekey) {
      var products = this.allProductList.filter((p) => p._preKey == prekey);

      //判断是否已经载入了数据，是则不重新载入
      if (products.length == 0) {
        //通过外部 loader 获取数据
        //leval+1 是为了方便调用者清楚对应的层级，但是实际上我们只处理  动态层级，即动态载入数据的 层级

        var product = this.allProductList.filter(
          (p) => p._fullKey == prekey
        )[0];

        this.dataLoader(
          product,
          product.key,
          product._fullKey.split(",").length,
          (productChildren) => {
            this.dataLoaderCallback(product, productChildren);

            this.selectAllCallback(
              checked,
              this.allProductList.filter((p) => p._preKey == prekey),
              prekey
            );
          }
        );
      } else {
        //如果是最后一级的数据，则标记勾选

        this.selectAllCallback(checked, products, prekey);
      }
    },

    isAllSelectdByLeval(leval) {
      if (!this.selectedItems[leval]) return false;
      return this.isAllSelectd(this.selectedItems[leval]._fullKey);
    },
    //判断是全选
    isAllSelectd(prekey) {
      //判断其子项下()是否都有载入完（有最后一项的数据  ）
      let _this = this;
      var childrenLoadInfo = this.allProductList
        .filter((p) => p._preKey == prekey) //获取到当前列
        .map((p) => {
          //遍历当前列的每一项，判断它们是否有载入子项
          return _this.allProductList.filter(
            (child) =>
              child._fullKey.indexOf(p._fullKey) == 0 && //是否是子项
              child._preKey.split(",").length == _this.levalCount //是否是最后一项
          ).length > 0
            ? 1
            : 0;
        });

      var products = this.allProductList.filter(
        (p) =>
          p._preKey.indexOf(prekey) == 0 &&
          p._fullKey.split(",").length == this.levalCount + 1
      );
      var selectedProducts = products.filter(
        (p) => p._preKey.indexOf(prekey) == 0 && p._selected
      );
      return (
        childrenLoadInfo.length != 0 &&
        childrenLoadInfo.length ==
          childrenLoadInfo.filter((load) => load).length &&
        products.length != 0 &&
        products.length == selectedProducts.length
      );
    },

    /*获取选中的总数  基于当前 product 子集的选中总数*/
    getSelectedCount(prekey) {
      return this.allProductList.filter(
        (p) => p._preKey.indexOf(prekey) == 0 && p._selected
      ).length;
    },

    // 获取所有选中的项
    getAllSeletedProducts() {
      var products = this.allProductList.filter((p) => p._selected);

      return products;
    },
    deleteFromAllSeletedProducts(key) {
      this.allProductList
        .filter((p) => p.key == key)
        .forEach((p) => {
          this.$set(p, "_selected", false);
        });
    },

    // 索引点击
    indexClick(key) {
      this.selectedIndex = key;
      //TODO 滚动品牌
    },
    // 显示已选

    showSelected() {

      // 所有选中项
      var products = this.getAllSeletedProducts();
      let _this = this;
      products.forEach((product) => {
        var fullkeys = product._fullKey.split(",");
        for (let i = 1; i < fullkeys.length; i++) {
          var p = _this.allProductList.filter((p) => p.key == fullkeys[i])[0];
          _this.$set(product, "_column_" + (i-1), p.name);
        }
      });
      this.allSelectedProducts4Table= products;


      // 列

      var colums = [];
      if (this.allSelectedProducts && this.allSelectedProducts.length > 0) {
        for (let i = 0; i < this.selectedTableColumnTitles.length - 1; i++) {
          colums.push({
            title: this.selectedTableColumnTitles[i],
            dataIndex:"_column_" + i,
            key: 'key'
          });
        }

        colums.push({
          title: this.selectedTableColumnTitles[this.selectedTableColumnTitles.length - 1],
          dataIndex: 'name',
          key: "name",
        });

      }

      colums.push({
        title: "Action",
        key: "action",
        scopedSlots: { customRender: "action" },
      });

      this.tableColums = colums;

      this.isShowSelected = true;
    },
    checkAll(checked) {
      //TODO
      if (checked) this.data.forEach((d) => this.selectAll(true, d._fullKey));
      else this.allProductList.forEach((p) => (p._selected = false));
    },
  },
};
</script>

<style scoped lang="less">
.content,
.content-row {
  height: 100%;
}
li {
  list-style-type: none;
}
/* 索引列 */
.col-index {
  background: #f6f7fa;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #9aa3b6;
}
.col-index {
  ul {
    padding: 0px;
    display: flex;
    flex-direction: column;
  }
  li {
    cursor: pointer;
  }
}
.col-products {
  ul {
    padding: 0px;
    display: flex;
    flex-direction: column;
  }
  li {
    cursor: pointer;
  }
}

/* 选中的产品项 */
.productActive {
  color: coral;
}
</style>
